import 'dart:typed_data';

import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/tools/blue/blue_config.dart';
import 'package:dmz/tools/blue/blue_manger.dart';
import 'package:dmz/tools/blue/blue_tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class EMIBlueBusiness {
  ///蓝牙操作
  static Future<void>? deviceOperate(String snCode, EMIBlueACT action,
      {int? sensitive,
      bool isOpen = true,
      int? otherData,
      Function(String content)? callback}) {
    return EMIBlueMangered().sendData(snCode,
        action: action, otherSetData: otherData, callback: callback);
  }

  ///获取写入操作指令
  static List<int> getWriteData(EMIBlueACT action,
      {int? sensitive, bool isOpen = true, int? otherData}) {
    switch (action) {
      case EMIBlueACT.authentication:
        print('授权指令 ---');
        return EMIBlueInstruction.authentication;
      case EMIBlueACT.setDeviceOpen:
        List<int> data = EMIBlueInstruction.setDeviceOpen;
        // data.add(isOpen ? 1 : 0);
        return data;
      case EMIBlueACT.setDeviceClose:
        return EMIBlueInstruction.setDeviceClose;
      case EMIBlueACT.erssiIrkOpen:
        return EMIBlueInstruction.erssiIrkOpen;
      case EMIBlueACT.erssiIrkClose:
        return EMIBlueInstruction.erssiIrkClose;
      case EMIBlueACT.stareFoundDevice:
        return EMIBlueInstruction.stareFoundDevice;
      case EMIBlueACT.endFoundDevice:
        return EMIBlueInstruction.endFoundDevice;
      case EMIBlueACT.openTrunk:
        return EMIBlueInstruction.openTrunk;
      case EMIBlueACT.vibrateSensitive:
        List<int> data = List<int>.from(EMIBlueInstruction.vibrateSensitive);
        data.add(otherData!);
        return data;

      case EMIBlueACT.lockStatusChange:
        List<int> data = List<int>.from(EMIBlueInstruction.lockStatusChange);
        data.add(sensitive == 0 ? 0x01 : 0x00);
        return data;

      case EMIBlueACT.autoLock:
        List<int> data = List<int>.from(EMIBlueInstruction.autoLock);
        data.add(otherData!);
        return data;

      case EMIBlueACT.queryOpenStatus:
        return EMIBlueInstruction.queryOpenStatus;

      case EMIBlueACT.queryUnLockDistance:
        List<int> data = List<int>.from(EMIBlueInstruction.queryUnLockDistance);
        data.add(sensitive!);
        data.add(0);
        return data;
      case EMIBlueACT.bleUnlockDistance:
        List<int> data = List<int>.from(EMIBlueInstruction.bleUnlockDistance);
        // EMIBlueInstruction.bleUnlockDistance;
        data.add(otherData!);
        data.add(0);
        return data;

      case EMIBlueACT.queryVibrateSensitive:
        return EMIBlueInstruction.queryVibrateSensitive;

      case EMIBlueACT.queryRssiIrk:
        return EMIBlueInstruction.queryRssiIrk;

      case EMIBlueACT.queryElectrict:
        return EMIBlueInstruction.queryElectrict;

      case EMIBlueACT.queryElectrictStatus:
        return EMIBlueInstruction.queryElectrictStatus;

      case EMIBlueACT.queryDeviceSN:
        return EMIBlueInstruction.queryDeviceSN;

      case EMIBlueACT.queryDeviceCharacteristic:
        return EMIBlueInstruction.queryDeviceCharacteristic;

      case EMIBlueACT.queryDeviceNameAndVersion:
        return EMIBlueInstruction.queryDeviceNameAndVersion;

      case EMIBlueACT.queryDeviceOTAVersion:
        return EMIBlueInstruction.queryDeviceOTAVersion;

      case EMIBlueACT.queryLockStatus:
        return EMIBlueInstruction.queryLockStatus;

      case EMIBlueACT.query4GAndGPS:
        return EMIBlueInstruction.query4GAndGPS;
      case EMIBlueACT.restart:
        return EMIBlueInstruction.restart;

      default:
        return [];
    }
  }

  ///接收数据处理
  static didToCharacteristic(String snCode, List<int> data) {
    String resultFir = EMIBlueTool.deviceDataAnalysis([data.first]);
    debugPrint('蓝牙 数据----$resultFir');
    if (resultFir == 'aa') {
      //上报数据
      var canParse = parserBLEData(snCode, data);
      debugPrint('蓝牙 上报数据 $canParse $resultFir');
      if (canParse) {
        var key = EMIBlueTool.getCallBackKey(data);
        var callback = EMIBlueMangered().callbacks[key];
        var backs = EMIBlueMangered().callbacks;
        if (callback != null) {
          debugPrint('蓝牙回调222 ---$key $backs $data');
          callback(EMIBlueTool.dataContent(data));
        } else {
          debugPrint('蓝牙回调333 --- $data');
          if (EMIBlueTool.dataCmd(data) == "61") {
            debugPrint('启动返回');
          }
        }
      }
    } else if (resultFir == '7e') {
      //应答数据
      var key = EMIBlueTool.getCallBackKey(data);
      Function(String content)? callback = EMIBlueMangered().callbacks[key];
      debugPrint(
          '蓝牙 应答数据 --$key ${EMIBlueMangered().callbacks} ${callback != null}');
      // var backs = EMIBlueMangered().callbacks;
      if (callback != null) {
        debugPrint('蓝牙回调333 --- ');
        callback(EMIBlueTool.dataContent(data));
        EMIBlueMangered().callbacks.remove(key);
      }
    }
  }

  static bool parserBLEData(String snCode, List<int> data) {
    String cmd = EMIBlueTool.deviceDataAnalysis([data[3]]);
    debugPrint('蓝牙 收鉴权0000不处理 -$cmd');
    if (int.parse(cmd) == 1) {
      if (data.length >= 5) {
        String step = EMIBlueTool.deviceDataAnalysis([data[4]]);
        debugPrint('蓝牙 收鉴权111 step -$step');
        if (int.parse(step) == 1) {
          debugPrint('蓝牙 收鉴权2222 data.length -${data.length}');
          if (data.length == 22) {
            //设备登录
            bleLoginReply(snCode);
          } else {
            // DDLogInfo(@"======收鉴权01不处理");
            debugPrint('收鉴权01不处理');
          }
        } else if (int.parse(step) == 3) {
          if (data.length >= 21) {
            debugPrint('收鉴权03 ${data}-- ${EMIBlueMangered().bleLoginDete}');
            List<int> sendData = data.sublist(5);
            // String dataStr = EMIBlueTool.deviceDataAnalysis(sendData);
            //aes解密
            List<int> result =
                AESHelper.aes128CBCDecrypt(Uint8List.fromList(sendData));
            var list1 = EMIBlueMangered().bleLoginDete.sublist(0, 4);
            var list2 = result.sublist(0, 4);
            debugPrint(
                '收鉴权04 ${EMIBlueMangered().bleLoginDete.sublist(0, 4)}-- ${result.sublist(0, 4)}');
            if (EMIBlueTool.deviceDataAnalysis(list1) ==
                EMIBlueTool.deviceDataAnalysis(list2)) {
              bleLoginVerify(snCode);
            }
          }
        }
      }
      return false;
    }
    return true;
  }

  //设备登录
  static bleLoginReply(String snCode) {
    List<int> data = getTodayStrss();
    List<int> endData = EMIBlueInstruction.loginReply + data;
    debugPrint('设备登录');
    EMIBlueMangered().sendData(snCode, otherData: endData);
  }

  //设备登录校验
  static bleLoginVerify(String snCode) {
    List<int> endData = EMIBlueInstruction.loginVerify;
    debugPrint('设备登录校验');
    EMIBlueMangered().sendData(snCode, otherData: endData);
    Get.find<HomePageController>().getBLEData();
  }

  ///获取时间加密数据
  static List<int> getTodayStrss() {
    // 获取当前时间戳（秒）
    int timestampInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    String dateStr = timestampInSeconds.toRadixString(16);
    var intList = EMIBlueTool.turnSring16ToListInt(dateStr);
    EMIBlueMangered().bleLoginDete = intList;
    //aes加密
    var result = AESHelper.aes128CBCEncrypt(Uint8List.fromList(intList));
    debugPrint('设备登录 ---$result  $intList ${result.length}');
    return result;
  }
}
